<template>
  <div class="content" style="background: #fff;">
    <div class="page">
      <!--商品信息-->
      <div v-show="dataInfo != ''">
        <!-- <div class="info-store mb-24 pb-12 flex a-c j-sb" v-if="storeInfo && storeInfo.shopId">
          <div class="flex a-c f-1">
            <img v-if="storeInfo.shopImg" class="store-icon br-10" :src="storeInfo.shopImg" />
            <img v-else-if="dataInfo.channel && storeIcon[dataInfo.channel]" class="store-icon br-10"
              :src="require(`@/assets/images/${storeIcon[dataInfo.channel]}`)" />
            <div class="store-text ml-12 o-1 f-20 lin-28 bold col-1e1">
              {{ storeInfo.shopName || '' }}
            </div>
          </div>
          <div class="c-p btn-store bg-fdf col-ff1 br-6 plr-16 f-20 flex a-c j-c lin-20" @click="stoteDetail">
            {{ $t('store.goodsToStore') }}
          </div>
        </div> -->
        <div class="info">
          <div class="left">
            <div class="info-thumbs-box">

              <div class="main-swiper" id="main-swiper">
                <div v-show="!currentImage" class="swiper-wrapper">
                  <div class="swiper-slide" v-for="(item, index) in dataInfo.imageList" :key="index">
                    <img class="banner" :src="item" alt="">
                  </div>
                </div>
                <div v-show="currentImage" class="current-goods">
                  <img :src="currentImage" alt="">
                </div>
              </div>
              <div id="thumbs" class="thumbs-swiper">
                <div class="swiper-wrapper">
                  <div class="swiper-slide" @click="currentImage = ''" v-for="(item, index) in dataInfo.imageList"
                    :key="index * 10">
                    <img class="banner" :src="item" alt="">
                  </div>
                </div>
              </div>
            </div>
            <div class="share">
              <div class="share-item">
                <!-- 初版推广联盟分享奖励 -->
                <!-- <div class="btn" @click="shareBtn">
                  <span class="iconfont icon-fenxiang"></span>
                  {{ userInfo.isJoinedAlliance === 0 ? $t('promote.un_joined_text') : $t('promote.joined_show_text') }}
                  <img src="@/assets/images/promote/coin.png" class="coin-icon" v-if="userInfo.isJoinedAlliance === 1"
                    alt="">
                </div> -->
                <div class="btn" @click="shareMet">
                  <span class="iconfont icon-fenxiang"></span>
                </div>
              </div>
              <div class="share-item">
                <div class="btn" @click="onCollect">
                  <Icon type="md-heart" v-if="dataInfo.favorite" />
                  <Icon type="md-heart-outline" v-else />
                </div>
              </div>
            </div>
            <!-- 质检照片 -->
            <!-- <div class="pt-32">
							<div>
								<span class="col-1e1 f-20 lin-28">质检照片</span>
								<span class="ml-4 col-aeb f-18 lin-28">（样例）</span>
							</div>
							<div class="details-qc mt-20" id="qcDetail">
								<div class="swiper-wrapper">
								  <div 
										class="swiper-slide" 
										v-for="(item, index) in dataInfo.imageList" :key="index" 
										@click="qcPicture(index)" 
								    >
								    <img class="qc-banner br-12 c-p" :src="item" alt="">
								  </div>
								</div>
							</div>
						</div> -->
          </div>

          <div class="right" v-if="dataInfo">
            <good-info :info="dataInfo" @on-change="onGoodsImage" @refreshData="updateMet" @taobaoBuy="taobaoBuy"
              @taobaoAdd="taobaoAdd" @changePreVal="changePreVal" @upDataEmit="upDataEmit"
              :activityCode="activityCode"></good-info>

            <div class="goods-content" v-html="dataInfo.description"></div>
          </div>
        </div>
        <!--推荐-->
        <div class="recommend" v-if="false">
          <Tabs value="name1" :animated="false">
            <TabPane label="本地销量排序" name="name1">
              <hot-commodity></hot-commodity>
            </TabPane>
            <TabPane label="本店收藏排序" name="name2">
              <collect-commodity></collect-commodity>
            </TabPane>
          </Tabs>
        </div>
        <!-- 好物推荐商品 -->
        <!-- <goods-product :shopProductList="shopProductList"></goods-product> -->
        <!--简介-->
        <!-- <div class="intro">
          <div v-html="dataInfo.description" class="html-content"></div>
          <Tabs v-if="false" value="name1" :animated="false">
            <TabPane label="商品详情" name="name1">
              <div v-html="dataInfo.description"></div>
            </TabPane>
            <TabPane label="评论" name="name2">
              评论
            </TabPane>
            <TabPane label="规格参数" name="name3">
              规格参数
            </TabPane>
            <TabPane label="代购须知" name="name4">
              代购须知
            </TabPane>
            <TabPane label="售后服务" name="name5">
              售后服务
            </TabPane>
          </Tabs>
        </div> -->
      </div>
      <Spin size="large" fix v-if="loading"></Spin>
      <!-- 推广分享弹框 -->
      <share-com ref="shareRef" :info="dataInfo"></share-com>
      <!-- 二次改版推广分享弹框 -->
      <share-link-pop ref="shareLinkRef"></share-link-pop>
      <!-- 禁搜词黑名单 -->
      <tips-text ref="tipsPopRef"></tips-text>
      <!-- 禁搜词灰名单 -->
      <gray-list ref="grayPopRef"></gray-list>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Swiper from "swiper";
import "swiper/css/swiper.css";
import HotCommodity from "./hot-commodity";
import CollectCommodity from "./collect-commodity";
import GoodInfo from "@/views/main/goods/goods-details/good-info";
import GoodInfoSimple from "@/views/main/goods/goods-details/good-info-simple";
import { queryProductDetail, productShareBind, queryShopProductDetail } from "@/api/product";
import { favoritesAdd, favoritesDeleteBatch } from "@/api/favorites";
import { fromSeoFriendsChannel, toSeoFriendsChannel } from "@/common/common";
import tipsText from "../components/tips-text.vue";
import { toDetailPage, leaveDetailPage, detailPointBtn } from "@/common/point/taobao";//淘宝埋点
import ShareCom from './components/share-Com.vue';
import GrayList from '../components/gray-list.vue';
import goodsProduct from "./components/goods-product.vue";
import { detailPoint, userInfo } from '@/api/user';
import shareLinkPop from "@/views/main/activity/Promotion/components/share-link-pop.vue";
import { infoShop } from "@/api/product";
import { storeIcon } from '@/common/enum';

export default {
  name: "goods-details",
  components: { GoodInfo, CollectCommodity, HotCommodity, tipsText, ShareCom, GrayList, goodsProduct, shareLinkPop, GoodInfoSimple },
  data() {
    return {
      storeIcon,
      createForm: {
        type: 'GOODS',
      },
      loading: false,
      currentImage: '',
      channels: {
        "0": "1688",
        "1": "TAOBAO",
        "2": "WEIDIAN",
        "3": "JD"
      },
      currentSwiper: '',
      id: '', // 商品id
      channel: '',
      dataInfo: '', // 商品信息
      shopProductList: [],
      currentSelectInfo: {
        price: 0,
        priceCNY: 0,
        image: '',
        originalPriceCNY: 0,
        originalPrice: 0
      },
      afterPrice: '',
      activityCode: '',
      qcSwiper: '',
      storeInfo: {}
    }
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  created() {
    toDetailPage(this.$route.params.spuNo, localStorage.getItem("prevPage"));//淘宝埋点

    if (this.$route.params.spuNo) {
      this.id = this.$route.params.spuNo;
      this.channel = this.channels[this.$route.params.channel] || this.$route.params.channel;
    } else if (this.$route.query.spuNo) {
      this.id = this.$route.query.spuNo;
      this.channel = this.channels[this.$route.query.channel] || this.$route.query.channel;
    }
    else if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.channel = this.$route.query.channel;
    } else if (this.$route.query.channelId) {
      this.id = this.$route.query.spuNo;
      this.channel = this.channels[this.$route.query.channelId] || this.$route.query.channelId;
    }
    // 是否是拼团activityCode
    if (this.$route.query.activityCode) {
      this.activityCode = this.$route.query.activityCode;

      // 点击“邀请链接”或扫描“邀请海报”进入商品页的用户打点
      if (this.$analytics) {
        this.$analytics.logEvent('pt_1005');
      }
    }

    this.queryShopProductDetail();//商城详情页推荐
  },
  mounted() {
    this.onInit();
    this.getQueryProductDetail();
  },
  watch: {
    '$route'() {
      if (this.$route.params.spuNo) {
        this.id = this.$route.params.spuNo;
        this.channel = this.channels[this.$route.params.channel];
      } else if (this.$route.query.spuNo) {
        this.id = this.$route.query.spuNo;
        this.channel = this.channels[this.$route.query.channel] || this.$route.query.channel;
      }
      else if (this.$route.query.id) {
        this.id = this.$route.query.id;
        this.channel = this.$route.query.channel;
      } else if (this.$route.query.channelId) {
        this.id = this.$route.query.spuNo;
        this.channel = this.channels[this.$route.query.channelId];
      }
      this.getQueryProductDetail()
    },
    userInfo: {
      immediate: true, // 立即执行一次
      deep: true,
      handler(newVal) {
        if (Object.keys(newVal).length > 0) {
          if (newVal.inviteCode) {
            const searchParams = new URLSearchParams(new URL(window.location.href).search);// 解析URL获取查询参数
            const inviteCode = searchParams.get('inviteCode');// 获取inviteCode的值,如果有邀请码的话就调用产品分享绑定接口
            if (inviteCode !== this.userInfo.inviteCode) {
              this.getProductShareBind(inviteCode);
            }
          }
        }
      }
    },
    dataInfo: {
      immediate: true,
      handler(newVal) {
        if (newVal && newVal.shopId) {
          this.getStoreInfo();
        }
      }
    },
  },
  methods: {
    queryShopProductDetail() {
      queryShopProductDetail().then((res) => {
        this.shopProductList = res.result;
      })
    },
    // 淘宝购买按钮点击埋点
    taobaoBuy() {
      if (this.dataInfo.channel == 'TAOBAO') {
        detailPointBtn(this.$route.params.spuNo, 'CLK', 'buy_icon');
      }
    },
    // 淘宝加入购物车埋点
    taobaoAdd() {
      if (this.dataInfo.channel == 'TAOBAO') {
        detailPointBtn(this.$route.params.spuNo, 'CLK', 'addcart_icon');
      }
    },
    updateMet(newDate) {
      // 强制刷新
      this.getQueryProductDetail(true);
    },
    shareBtn() {
      // 0 未加入 1已加入
      if (this.userInfo.isJoinedAlliance === 1) {
        this.createForm.jsonDetail = JSON.stringify({ channel: toSeoFriendsChannel(this.channel), id: this.id });
        this.$refs.shareRef.open(this.createForm);
      } else {
        // 跳转到推广联盟
        const targetPage = `/Alliance`;
        window.open(targetPage, "_blank");
      }
    },
    shareMet() {
      this.createForm.jsonDetail = JSON.stringify({ channel: toSeoFriendsChannel(this.channel), id: this.id });
      this.$refs.shareLinkRef.open(this.createForm);
    },
    onCollect() {
      if (this.dataInfo.favorite) {
        this.deleteFavorites();
      } else {
        this.addFavorites();
      }
    },
    changePreVal(val) {
      this.afterPrice = val;
    },
    // 处理 price 值的方法
    getPriceValue() {
      if (this.dataInfo.price) {
        return this.dataInfo.priceCNY ? this.dataInfo.priceCNY : this.dataInfo.price;
      } else if (this.currentSelectInfo.price && this.afterPrice === '') {
        return this.currentSelectInfo.priceCNY ? this.currentSelectInfo.priceCNY : this.currentSelectInfo.price;
      } else if (this.afterPrice) {
        return this.afterPrice;
      } else if (this.dataInfo.saleInfo) {
        if (this.dataInfo.saleInfo.priceRangeList && this.dataInfo.saleInfo.priceRangeList.length > 0) {
          return this.dataInfo.saleInfo.priceRangeList[0].priceCNY ? this.dataInfo.saleInfo.priceRangeList[0].priceCNY : this.dataInfo.saleInfo.priceRangeList[0].price;
        } else {
          return this.dataInfo.saleInfo.priceRanges && this.dataInfo.saleInfo.priceRanges.length > 0 && this.dataInfo.saleInfo.priceRanges[0].priceCNY ? this.dataInfo.saleInfo.priceRanges[0].priceCNY : ""
        }
      }
      return null; // 如果以上条件都不满足，price 设为 null，可根据实际情况修改默认值
    },
    addFavorites() {
      console.log(this.dataInfo);

      // 收藏商品
      this.dataInfo.favorite = true;
      const dataObj = {
        channel: this.dataInfo.channel,
        targetId: this.dataInfo.spuNo,
        type: 'spu',
        subject: this.dataInfo.subject,
        mainImage: this.dataInfo.mainImg,
        price: this.getPriceValue(),
        detailUrl: this.dataInfo.detailUrl
      };
      // spu: 商品,shop店铺
      favoritesAdd(dataObj).then((res) => {
        if (res.code == 200) {
          this.$Message.success(res.result);
        }
      });
    },
    deleteFavorites() {
      // 删除收藏
      this.dataInfo.favorite = false;
      favoritesDeleteBatch([this.dataInfo.spuNo], 'spu');
    },
    onGoodsImage(info) {
      this.currentSelectInfo = info;
      this.currentImage = info.image;
    },
    onInit() {
      this.currentSwiper = new Swiper("#thumbs", {
        direction: 'vertical',
        observer: true, // 修改swiper自己或子元素时，自动初始化swiper
        observeParents: true, // 修改swiper的父元素时，自动初始化swiper
        spaceBetween: 10,
        slidesPerView: 4,
        freeMode: true,
        watchSlidesProgress: true,
      });
      let swiper2 = new Swiper("#main-swiper", {
        observer: true, // 修改swiper自己或子元素时，自动初始化swiper
        observeParents: true, // 修改swiper的父元素时，自动初始化swiper
        spaceBetween: 10,
        navigation: {
          nextEl: ".swiper-button-next",
          prevEl: ".swiper-button-prev",
        },
        thumbs: {
          swiper: this.currentSwiper,
        }
      });
      // this.qcSwiper = new Swiper("#qcDetail", {
      //   observer: true, // 修改swiper自己或子元素时，自动初始化swiper
      //   observeParents: true, // 修改swiper的父元素时，自动初始化swiper
      //   spaceBetween: 10,
      //   slidesPerView: 4,
      //   freeMode: true,
      //   watchSlidesProgress: true,
      // });
    },
    getQueryProductDetail(force) {
      // 商品详情
      this.loading = true;
      queryProductDetail({
        spuNo: this.id,
        refresh: !!force ? 1 : 0,
        channel: this.channel,
        activityCode: this.activityCode
      }).then((res) => {
        // 禁搜词黑名单
        if (res.code == 1010) {
          this.loading = false;
          this.$refs.tipsPopRef.open(res.message);
        } else if (res.code == 200) {
          //禁搜词灰度名单是否显示
          if (res.result.productGrayscale) {
            this.$refs.grayPopRef.open(res.result.productGrayscaleName)
          }

          this.loading = false;
          this.dataInfo = res.result;
          this.dataInfo.description = this.dataInfo.description.replace(/\s*href="[^"]*"/gi, '');

          if (this.dataInfo.channel == 'TAOBAO') {
            // 淘宝埋点
            detailPointBtn(this.$route.params.spuNo, 'EXP', 'buy_icon');//购买按钮曝光
            detailPointBtn(this.$route.params.spuNo, 'EXP', 'addcart_icon');//加入购物车按钮曝光
          }

          // 用户每次进入拼团商品详情页打点
          if (res.result.spuActivityVO) {
            if (this.$analytics) {
              this.$analytics.logEvent('pt_1001');
            }
          }
        } else {
          // 无操作
          // banned-words组件是弹框，后续会用到
        }
      }).catch(() => {
        this.loading = false;
      })
    },
    upDataEmit() {
      let newQuery = JSON.parse(JSON.stringify(this.$route.query));
      delete newQuery.activityCode;
      this.$router.replace({ query: newQuery });
      this.activityCode = '';
      // this.dataInfo = '';//这个会让loading显示出来
      this.getQueryProductDetail();
    },
    // 产品分享绑定
    getProductShareBind(inviteCode) {
      let data = {
        channel: 5,
        detailUrl: window.location.href,
        productChannel: this.channel,
        spuNo: this.id
      }
      detailPoint(data)
      productShareBind({ inviteCode: inviteCode, spuNo: this.id })
    },
    // 查看图片
    qcPicture(index) {
      this.$viewerApi({
        images: this.dataInfo.imageList,
        options: {
          initialViewIndex: index,
        },
      });
    },
    getStoreInfo() {
      let data = {
        channel: this.dataInfo.channel,
        shopId: this.dataInfo.shopId
      }
      infoShop(data).then(res => {
        this.storeInfo = res.result;
      })
    },
    //进入店铺
    stoteDetail() {
      if (this.$analytics) {
        this.$analytics.logEvent('dy_3006');
      }
      this.$router.push(`/store?shopId=${this.storeInfo.shopId}&channel=${this.dataInfo.channel}`)
    }
  },
  beforeDestroy() {
    leaveDetailPage(this.$route.params.spuNo, localStorage.getItem("prevPage"));//淘宝埋点
  }
}
</script>

<style scoped lang="less">
.page {
  margin: 0 auto;
  overflow: hidden;
  min-height: 966px;
  width: 1310px;

  .position-content {
    height: 300px;
  }

  .info-store {
    border-bottom: 1px solid #E9EAF3;

    .store-icon {
      width: 52px;
      height: 52px;
    }

    .store-text {
      max-width: 800px;
    }

    .btn-store {
      height: 44px;
      border: 1px solid #FF186B;

      &:hover {
        color: #FF186B;
      }
    }
  }

  .info {
    margin-top: 40px;
    display: flex;
    flex-shrink: 0;
    position: relative;

    .left {
      width: 539px;
      overflow: hidden;

      .info-thumbs-box {

        .main-swiper {
          width: 539px;
          height: 539px;
          overflow: hidden;
          border-radius: 2px;
          margin-bottom: 32px;

          .swiper-slide {
            display: flex;
            align-items: center;
            justify-content: center;

            img {
              display: block;
              width: 100%;
            }
          }

          .current-goods {
            img {
              display: block;
              width: 100%;
              border: none;
              border-radius: 11px;
            }
          }
        }

        .thumbs-swiper {
          // width: 60px;
          // width: 40px;
          box-sizing: border-box;
          height: 95px;

          // height: 0px;

          .swiper-wrapper {
            display: flex;
            align-items: center;
            flex-direction: row;
          }

          .swiper-slide {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 95px !important;
            width: 95px !important;
            border-radius: 2px;
            margin-right: 16px;

            img {
              display: block;
              width: 100%;
              height: 100%;
              cursor: pointer;
              border-radius: 10px;
            }

            &:last-child {
              margin-right: 0;
            }
          }

          .swiper-slide-thumb-active {
            opacity: 0.6;
          }

        }

      }


    }

    .details-qc {
      .qc-banner {
        width: 100%;
        object-fit: cover;
      }
    }

    .share {
      position: absolute;
      left: 20px;
      top: 20px;

      .share-item {
        display: flex;
        width: 35px;
        height: 35px;
        background-color: #fff;
        border-radius: 50%;
        align-items: center;
        justify-content: center;
        margin-bottom: 12px;
        cursor: pointer;
        font-size: 20px;
      }

      .search-btn {
        width: 90px;
      }

      .share-left {
        .btn {
          cursor: pointer;
          color: #FF186B;
          font-size: 19px;
          font-weight: 400;
          line-height: 22px;
          font-family: PingFang HK, PingFang HK;
          display: inline-flex;
          align-items: center;
          gap: 6px;

          .iconfont {
            font-size: 19px;
          }

          .coin-icon {
            width: 19px;
            height: 19px;
          }
        }
      }

      .share-right {
        display: flex;
        align-items: center;

        .btn {
          margin-left: 24px;
          cursor: pointer;
          color: #FF186B;
          font-size: 19px;
          font-weight: 400;
          line-height: 22px;
          font-family: PingFang HK, PingFang HK;
        }
      }
    }

    .html-content {
      :deep(img) {
        width: 790px;
        text-align: center;
      }
    }

    .right {
      flex: 1;
      padding-left: 40px;
      position: relative;
      overflow: hidden;
    }
  }

  .intro {
    width: 790px;
    margin: 0 auto;
    margin-top: 32px;

    .html-content {
      :deep(img) {
        width: 790px;
        text-align: center;
      }
    }
  }

  .goods-content {
    overflow: hidden;

    /deep/ img {
      max-width: 100% !important;
    }
  }
}
</style>